package com.itheima.integration.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.integration.pojo.User;
import com.itheima.integration.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询所有的用户
     * @return
     */
    //@RequestMapping("/findAllUser")
    //public List<User> findAllUser() {
    //
    //    //调用service层的方法
    //    List<User> user = userService.findAllUser();
    //    return user;
    //}
    @RequestMapping("/findAllUser")
    public String findAllUser() {
        /**
         * 1.redis中查询数据
         * 2.有数据->>>>>直接返回
         * 3.无数据->>>>>
         *          数据库查询
         *          对象转成字符串，存放到redis中
         *          返回结果
         */
        String userStr = (String) redisTemplate.boundValueOps("userAll").get();
        if (!StringUtils.hasLength(userStr)) {
            System.out.println("从数据库中查找");
            List<User> user = userService.findAllUser();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                userStr = objectMapper.writeValueAsString(user);
                redisTemplate.boundValueOps("userAll").set(userStr);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error(" ", e);
            }
        }
        return userStr;
    }
}
